<template>
  <div>
    <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <!-- 高级筛选 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            v-model="queryInfo.query"
            placeholder="请输入关键字"
            clearable
            @clear="getUsers"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUsers()"
            ></el-button>
          </el-input>
        </el-col>

        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible = true"
            >添加用户</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格数据 -->
      <el-table :data="userList" border style="width: 100%">
        <el-table-column type="index" label="序号" width="60"></el-table-column>
        <el-table-column prop="username" label="用户名称" width="180">
        </el-table-column>
        <el-table-column prop="email" label="邮箱" width="180">
        </el-table-column>
        <el-table-column prop="mobile" label="手机号码" width="180">
        </el-table-column>
        <el-table-column prop="role_name" label="权限"> </el-table-column>
        <el-table-column prop="create_time" label="创建时间"></el-table-column>
        <el-table-column prop="mg_state" label="启用状态">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="hanldeChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>

        <el-table-column label="操作" width="176px">
          <template slot-scope="scope">
            <div>
              <el-tooltip
                effect="dark"
                content="编辑"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="editUser(scope.row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="删除"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="delByUserId(scope.row.id)"
                ></el-button>
              </el-tooltip>
              <el-tooltip
                effect="dark"
                content="设置角色"
                placement="top"
                :enterable="false"
              >
                <el-button
                  type="warning"
                  icon="el-icon-share"
                  size="mini"
                  @click="setUserRole(scope.row)"
                ></el-button>
              </el-tooltip>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="paginationPage">
        <span>总页数：{{ total }}</span>
        <el-pagination
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryInfo.pagenum"
          :page-sizes="[2, 3, 4, 5]"
          :page-size="queryInfo.pagesize"
          layout=" sizes, prev, pager, next, jumper"
          :total="total"
        >
        </el-pagination>
      </div>
    </el-card>
    <!-- 添加用户弹窗 -->
    <el-dialog
      title="添加用户"
      :visible.sync="addDialogVisible"
      width="40%"
      @close="addDialogClose"
    >
      <!-- 主体内容部分 -->
      <el-form
        :model="addForm"
        :rules="addFormRules"
        ref="addFormRef"
        label-width="18%"
      >
        <el-form-item label="用户名称" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="用户密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 编辑用户弹窗 -->
    <el-dialog
      title="编辑用户"
      :visible.sync="editDialogVisible"
      width="40%"
      @close="editDialogClose"
    >
      <!-- 主体内容部分 -->
      <el-form
        :model="editForm"
        :rules="editFormRules"
        ref="editFormRef"
        label-width="18%"
      >
        <el-form-item label="用户名称">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <!-- 底部按钮部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editSaveUser">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 分配用户角色 -->
    <el-dialog
      title="设置角色"
      :visible.sync="setDialogVisible"
      width="40%"
      @close="setDialogClose"
    >
      <!-- 主体内容部分 -->
      <el-row>
        <span>用户id：{{ setUser.id }}</span>
      </el-row>
      <el-row>
        <span
          ><span>用户名称：{{ setUser.username }}</span></span
        >
      </el-row>
      <el-row>
        <el-select
          v-model="selectRolesId"
          :placeholder="placeholder"
          @change="changeRolesValue"
        >
          <el-option
            v-for="item in getRoles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          >
          </el-option>
        </el-select>
      </el-row>

      <!-- 底部按钮部分 -->
      <span slot="footer" class="dialog-footer">
        <el-button @click="setDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="setSaveUser">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    // 验证邮箱的规则
    var checkEmail = (rules, value, cb) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/;
      if (regEmail.test(value)) {
        // 合法的邮箱
        return cb();
      }
      cb(new Error("邮箱格式不正确"));
    };
    // 验证手机的规则
    var checkMobile = (rules, value, cb) => {
      const regMobile =
        /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/;
      if (regMobile.test(value)) {
        // 合法的邮箱
        return cb();
      }
      cb(new Error("邮箱格式不正确"));
    };
    return {
      userList: [],
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 2,
      },
      total: 0,
      addDialogVisible: false,
      editDialogVisible: false,
      setDialogVisible: false,
      selectRolesId: "",
      addForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },
      editForm: {},
      addFormRules: {
        username: [
          { required: true, message: "用户名不能为空", trigger: "blur" },
          { min: 3, max: 10, message: "字符长度在3-10之间", trigger: "blur" },
        ],
        password: [
          { required: true, message: "密码不能为空", trigger: "blur" },
          { min: 6, max: 15, message: "密码长度在5-10之间", trigger: "blur" },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "请输入正确的邮箱格式",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          {
            validator: checkMobile,
            message: "请输入正确的手机格式",
            trigger: "blur",
          },
        ],
      },
      editFormRules: {
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          {
            validator: checkEmail,
            message: "请输入正确的邮箱格式",
            trigger: "blur",
          },
        ],
        mobile: [
          { required: true, message: "请输入手机", trigger: "blur" },
          {
            validator: checkMobile,
            message: "请输入正确的手机格式",
            trigger: "blur",
          },
        ],
      },
      setUser: {},
      placeholder: "请选择",
    };
  },
  created() {
    this.getUsers();
    this.getRoles();
  },

  methods: {
    //修改用户状态
    async hanldeChange(rouUser) {
      console.log(rouUser);
      const { data: res } = await this.$http.put(
        "users/" + rouUser.id + "/state/" + rouUser.mg_state
        /* `users/${rouUser.id}/state/${rouUser.mg_state}` */
      );
      if (res.meta.status !== 200) {
        rouUser.mg_state = !rouUser.mg_state;
        return this.$message.error("用户状态修改未成功！");
      }
      this.$message.success("用户状态修改成功");
    },
    handleSizeChange(newSize) {
      //console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = newSize;
      this.getUsers();
    },
    handleCurrentChange(newPage) {
      //console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = newPage;
      this.getUsers();
    },
    async getUsers() {
      const { data: res } = await this.$http.get("/users", {
        params: this.queryInfo,
      });
      console.log(res);
      if (res.meta.status != 200)
        return this.$message.error("获取用户信息失败");
      this.userList = res.data.users;
      this.total = res.data.total;
      this.currentPage4 = res.data.pagenum;
    },
    //监听添加用户对话框
    addDialogClose() {
      this.$refs.addFormRef.resetFields();
    },
    //添加用户！
    addUser() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.post("/users", this.addForm);
        console.log(res);
        if (res.meta.status !== 201) {
          return this.$message.error("添加用户失败");
        }
        this.$message.success("添加用户成功");
        this.addDialogVisible = false;
        //重新获取数据列表
        this.getUsers();
      });
    },
    //编辑用户信息弹窗
    async editUser(id) {
      //console.log(id);
      this.editDialogVisible = true;
      const { data: res } = await this.$http.get("/users/" + id);
      //console.log(res);
      if (res.meta.status !== 200) return this.$message.error("获取信息失败");
      this.editForm = res.data;
    },
    /* 编辑用户信息 */
    editSaveUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        const { data: res } = await this.$http.put(
          "/users/" + this.editForm.id,
          {
            email: this.editForm.email,
            mobile: this.editForm.mobile,
          }
        );

        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.$message.success(res.meta.msg);
        this.editDialogVisible = false;
        this.getUsers();
      });
    },
    //重置编辑样式
    editDialogClose() {
      this.$refs.editFormRef.resetFields();
    },
    /*  */
    async delByUserId(id) {
      console.log(id);
      const confirmResult = await this.$confirm(
        "此操作将永久删除该数据, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => {
        return error;
      });
      //this.$message.info("已取消删除！");
      console.log(confirmResult);
      if (confirmResult !== "confirm")
        return this.$message.info("已取消删除！");

      const { data: res } = await this.$http.delete("/users/" + id);
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getUsers();
    },
    /* 分配角色设置 */
    setUserRole(user) {
      this.setUser = user;
      this.setDialogVisible = true;
      if (this.setUser.role_name !== "") {
        return (this.placeholder = this.setUser.role_name);
      }
    },
    /* 获取角色数数据信息 */
    async getRoles() {
      const { data: res } = await this.$http.get("roles");
      if (res.meta.status !== 200) {
        this.$message.error("用户权限获取失败！");
      }
      this.getRoles = res.data;
    },
    /* 获取下拉框的值 */
    changeRolesValue(val) {
      console.log(val);
      this.selectRolesId = val;
    },
    /* 保存角色设置 */
    async setSaveUser() {
      if (!this.selectRolesId) {
        return this.$message.error("请选择要分配的角色！");
      }
      const { data: res } = await this.$http.put(
        `users/${this.setUser.id}/role`,
        {
          rid: this.selectRolesId,
        }
      );
      if (res.meta.status !== 200) {
        return this.$message.error("分配角色失败！");
      }
      this.$message.success("角色分配成功");
      this.getUsers();
      this.setDialogVisible = false;
    },
    setDialogClose() {
      this.setUser = {};
      this.selectRolesId = "";
    },
  },
};
</script>
<style lang="less" scoped>
.el-table {
  margin-top: 15px;
}
.paginationPage {
  display: flex;
  justify-content: space-between;
  span {
    display: flex;
    margin-top: 15px;
    font-size: 13px;
    align-items: center;
  }
}
</style>
